package com.uidt.project.system.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

import com.uidt.framework.security.service.SysRegisterService;
import com.uidt.project.ptsj.domain.HouseInfo;
import com.uidt.project.ptsj.domain.PlaceInfo;
import com.uidt.project.ptsj.mapper.HouseInfoMapper;
import com.uidt.project.ptsj.mapper.PlaceInfoMapper;
import com.uidt.project.system.service.ISysUserService;
import com.uidt.project.system.service.impl.SysUserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.uidt.common.constant.Constants;
import com.uidt.common.utils.SecurityUtils;
import com.uidt.framework.security.LoginBody;
import com.uidt.framework.security.service.SysLoginService;
import com.uidt.framework.security.service.SysPermissionService;
import com.uidt.framework.web.domain.AjaxResult;
import com.uidt.project.system.domain.SysMenu;
import com.uidt.project.system.domain.SysUser;
import com.uidt.project.system.service.ISysMenuService;

/**
 * 登录验证
 * 
 * @author uidt
 */
@RestController
public class SysLoginController
{
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private SysRegisterService registerService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private HouseInfoMapper houseInfoMapper;

    @Autowired
    private PlaceInfoMapper placeInfoMapper;

    private static String deadLineStr = "2025-06-15 00:00:00";

    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    /**
     * 管理后台登录方法
     *
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody LoginBody loginBody)
    {
        try{
            Date now = new Date();
            Date deadTime = sdf.parse(deadLineStr);
            if(now.after(deadTime)){
                return AjaxResult.error("系统错误，请联系管理员");
            }
        }catch (Exception e){

        }

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
    /**
     * 登录方法，监管员登录
     * 
     * @param loginBody 登录信息
     * @return 结果
     */
    @PostMapping("/appCodeLoginForFrame")
    public AjaxResult appCodeLoginForFrame(@RequestBody LoginBody loginBody)
    {
        try{
            Date now = new Date();
            Date deadTime = sdf.parse(deadLineStr);
            if(now.after(deadTime)){
                return AjaxResult.error("系统错误，请联系管理员");
            }
        }catch (Exception e){

        }

        // 判断监管员当前扫码的房源场所，是否是他所属单位管辖的
        SysUser user = sysUserService.selectUserByUserName(loginBody.getUsername());

        if(user!=null){
            String deptcode = user.getDept().getDeptcode();
            if(!deptcode.startsWith("330900")){
                // 非市局用户需要进行判断
                String houseCode = loginBody.getHouseCode();
                HouseInfo houseInfo = houseInfoMapper.selectHouseInfoByHouseCode(houseCode);
                if("000000".equals(deptcode.substring(6,12)) ){
                    // 区县用户,用户单位代码前6位和房源管辖单位前6位必须一样，否则不能登录
                    if(!houseInfo.getGxdwdm().startsWith(deptcode.substring(0,6))){
                        return AjaxResult.error("对不起，当前场所不在管辖范围内，无法登录！");
                    }
                }else if("0000".equals(deptcode.substring(8,12))){
                    // 派出所用户,用户单位代码和房源管辖单位位必须一样，否则不能登录
                    if(!houseInfo.getGxdwdm().startsWith(deptcode.substring(0,12))){
                        return AjaxResult.error("对不起，当前场所不在管辖范围内，无法登录！");
                    }
                }
            }
        }

        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     * 
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     * 
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        Long userId = SecurityUtils.getUserId();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    /*
    * 游客登录逻辑
    * */
    @PostMapping("/appCodeLoginForTravel")
    public AjaxResult appCodeLoginForTravel(@RequestBody LoginBody loginBody) {
        try{
            Date now = new Date();
            Date deadTime = sdf.parse(deadLineStr);
            if(now.after(deadTime)){
                return AjaxResult.error("系统错误，请联系管理员");
            }
        }catch (Exception e){

        }
        AjaxResult ajax = AjaxResult.success();

        // 首先判断当前手机号是否是经营者之一
        PlaceInfo placeInfo = new PlaceInfo();
        placeInfo.setPhone(loginBody.getUsername());
        List<PlaceInfo> placeInfoList = placeInfoMapper.selectPlaceInfoList(placeInfo);
        if(placeInfoList!=null && placeInfoList.size()>0){
            return AjaxResult.error("对不起，您是作为场所经营者，无法用游客身份登录！");
        }

        //首先判断用户是否已经注册，如果已经注册直接登录，如果没有，现在注册后登录掉
        SysUser user = sysUserService.selectUserByUserName(loginBody.getUsername());

        if(user==null){
            // 先注册
            loginBody.setPassword("ptsj12345678");
//            游客部门207
            registerService.AppRegister(loginBody,207);
        }

        // 生成令牌
        String token = loginService.appCodeLogin(loginBody.getUsername(), loginBody.getCode(), loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /*
     * 业主登录逻辑
     * */
    @PostMapping("/appCodeLoginForYz")
    public AjaxResult appCodeLoginForYz(@RequestBody LoginBody loginBody) {
        try{
            Date now = new Date();
            Date deadTime = sdf.parse(deadLineStr);
            if(now.after(deadTime)){
                return AjaxResult.error("系统错误，请联系管理员");
            }
        }catch (Exception e){

        }
        AjaxResult ajax = AjaxResult.success();

        // 首先判断当前手机号和houseCode对应的场所经营者号码是否一致
        HouseInfo houseInfo = houseInfoMapper.selectHouseInfoByHouseCode(loginBody.getHouseCode());
        if(houseInfo==null){
            return AjaxResult.error("对不起，无当前房源信息，无法登录！");
        }
        PlaceInfo placeInfo = placeInfoMapper.selectPlaceInfoByPlaceCode(houseInfo.getPlaceCode());
        if(placeInfo==null){
            return AjaxResult.error("对不起，无当前场所信息，无法登录！");
        }
        if(!loginBody.getUsername().equals(placeInfo.getPhone())){
            return AjaxResult.error("对不起，您不是当前场所的经营者，无法登录！");
        }

        //首先判断用户是否已经注册，如果已经注册直接登录，如果没有，现在注册后登录掉
        SysUser user = sysUserService.selectUserByUserName(loginBody.getUsername());

        if(user==null){
            // 先注册
            loginBody.setPassword("ptsj12345678");
            // 业务部门208
            registerService.AppRegister(loginBody,208);
        }

        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }
}
